package com.jessechanrui.template.req15;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;






























import javafx.scene.text.Text;

import javax.imageio.ImageIO;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.codehaus.plexus.util.FileUtils;

import sun.java2d.pipe.CompositePipe;
import sun.java2d.pipe.TextRenderer;
import sun.misc.BASE64Encoder;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.agree.bos.bpbc.service.IBpbcPdfSerevice;
import com.agree.bos.bpbc.service.IBpbcTxtSerevice;
import com.agree.bos.communication.natp.CommunicationNatp;
import com.agree.bos.nsh.model.AfaCzedxzpTxnjnl;
import com.agree.bos.nsh.service.IBlackAshListSerevice;
import com.agree.framework.dao.entity.Page;
import com.agree.framework.exception.AppException;
import com.agree.framework.web.service.base.BaseService;
import com.agree.util.PropertiesUtils;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
//import com.itextpdf.text.pdf.qrcode.BitMatrix;
//import com.itextpdf.text.pdf.qrcode.EncodeHintType;
//import com.itextpdf.text.pdf.qrcode.ErrorCorrectionLevel;

public class BpbcTxtSerevice extends BaseService implements IBpbcTxtSerevice{
	private static Logger logger = Logger.getLogger(BpbcTxtSerevice.class);
	private static List list = new ArrayList();

	/**
	 * @category BEC_SCPDF WFI文本生成
	 * @param busidate
	 *            入参|业务日期|{@link String}
	 * @return 0 失败<br/>
	 *         1 成功<br/>
	 * @throws DocumentException 
	 * @throws IOException 
	 */
	@Override
	public boolean createTxt(JSONObject json) throws Exception {
		logger.error(json);
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		Date date = new Date();
		//String workdate=format.format(date);
		String workdate=json.getString("workdate");
		String outputfilePath = json.getString("pdffilepath")+"CCCS_"+workdate+".TXT";
		String csvEncode = (String) json.get("csvEncode");//文件编码
		byte[] bomByte = null;
		String bomStr = "";
		
		String outputPath = json.getString("pdffilepath")+workdate+"\\";
		File saveDir1 = new File(outputPath);
		File dir1 = saveDir1.getParentFile();
		dir1.mkdir();
		saveDir1.mkdir();
		

		//如果没有则创建
		File saveDir = new File(outputfilePath);
		File dir = saveDir.getParentFile();
		if(!dir.exists()){
			dir.mkdirs();
			System.out.println("创建");
		}else{
			new File(outputfilePath).delete();
			dir.mkdirs();
			System.out.println("先删除后创建");
		}
		
		File file = new File(outputfilePath);
		String _strToFile_ = "";
		BufferedWriter bufout = null;
		boolean append = false;
		if (file.exists()) {
			append = true;
		}
		if(json != null && !json.equals("{}")){
			_strToFile_ = "H"+workdate+"\n";
			int count = 0;//数据记录数
			
			if((int)json.get("extconfbook_num") > 0){
				List extconfbook_list = (List)json.get("extconfbook");
				logger.error(extconfbook_list.size());
				for(int o=0; o<extconfbook_list.size();o++){
					List l = (List)extconfbook_list.get(o);
					String hzbh = (String)l.get(0);
					if(l.get(8).equals("8-已完成")){
						_strToFile_ = _strToFile_ + "D*+"+hzbh +"*+";//函证编号
						String Pdffilename = hzbh+".pdf";
						String Csvfilename = hzbh+".csv";
						String UpdateCsvfilename = "(update)"+hzbh+".csv";
						String Pdfsha256 = sha256(json.getString("pdffilepath")+Pdffilename);
						_strToFile_ = _strToFile_ + Pdfsha256+"*+";//文件sha256
						if(Pdfsha256.equals("")){
							Pdffilename = "";
						}else{
							File saveDir2 = new File(json.getString("pdffilepath")+Pdffilename);
							File saveDir3 = new File(outputPath+Pdffilename);
							FileUtils.copyFile(saveDir2, saveDir3);
							int a = saveDir2.getCanonicalPath().compareTo(saveDir3.getCanonicalPath());
							logger.info("调用开始"+a);
						}
						_strToFile_ = _strToFile_ + Pdffilename+"*+";//文件名
						_strToFile_ = _strToFile_ + (String)l.get(1)+"*+";//分行代码
						_strToFile_ = _strToFile_ + (String)l.get(2)+"*+";//客户号
						_strToFile_ = _strToFile_ + (String)l.get(3)+"*+";//公司名称
						_strToFile_ = _strToFile_ + (String)l.get(4)+"*+";//方式
						_strToFile_ = _strToFile_ + (String)l.get(5)+"*+";//申请日
						_strToFile_ = _strToFile_ + (String)l.get(6)+"*+";//完成日
						_strToFile_ = _strToFile_ + (String)l.get(7)+"*+";//退回日
						_strToFile_ = _strToFile_ + (String)l.get(8)+"\n";//状态
						count = count +1;
						//logger.debug("调用afe开始");
						//toAfe(json.getString("pdffilepath")+Pdffilename);
						//logger.debug("调用afe结束");
						String Csvsha256 = sha256(json.getString("pdffilepath")+Csvfilename);
						_strToFile_ = _strToFile_ + "D*+"+ hzbh +"*+";//函证编号
						_strToFile_ = _strToFile_ + Csvsha256+"*+";//文件sha256
						if(Csvsha256.equals("")){
							Csvfilename = "";
						}else{
							File saveDir2 = new File(json.getString("pdffilepath")+Csvfilename);
							File saveDir3 = new File(outputPath+Csvfilename);
							FileUtils.copyFile(saveDir2, saveDir3);
							int b = saveDir2.getCanonicalPath().compareTo(saveDir3.getCanonicalPath());
							logger.info("调用开始"+b);
						}
						_strToFile_ = _strToFile_ + Csvfilename+"*+";//文件名
						_strToFile_ = _strToFile_ + (String)l.get(1)+"*+";//分行代码
						_strToFile_ = _strToFile_ + (String)l.get(2)+"*+";//客户号
						_strToFile_ = _strToFile_ + (String)l.get(3)+"*+";//公司名称
						_strToFile_ = _strToFile_ + (String)l.get(4)+"*+";//方式
						_strToFile_ = _strToFile_ + (String)l.get(5)+"*+";//申请日
						_strToFile_ = _strToFile_ + (String)l.get(6)+"*+";//完成日
						_strToFile_ = _strToFile_ + (String)l.get(7)+"*+";//退回日
						_strToFile_ = _strToFile_ + (String)l.get(8)+"\n";//状态
						count = count +1;
						
						String UpdateCsvsha256 = sha256(json.getString("pdffilepath")+UpdateCsvfilename);
						_strToFile_ = _strToFile_ + "D*+"+ hzbh +"*+";//函证编号
						_strToFile_ = _strToFile_ + UpdateCsvsha256+"*+";//文件sha256
						if(UpdateCsvsha256.equals("")){
							UpdateCsvfilename = "";
						}else{
							File saveDir2 = new File(json.getString("pdffilepath")+UpdateCsvfilename);
							File saveDir3 = new File(outputPath+UpdateCsvfilename);
							FileUtils.copyFile(saveDir2, saveDir3);
							int c = saveDir2.getCanonicalPath().compareTo(saveDir3.getCanonicalPath());
							logger.info("调用开始"+c);
						}
						_strToFile_ = _strToFile_ + UpdateCsvfilename+"*+";//文件名
						_strToFile_ = _strToFile_ + (String)l.get(1)+"*+";//分行代码
						_strToFile_ = _strToFile_ + (String)l.get(2)+"*+";//客户号
						_strToFile_ = _strToFile_ + (String)l.get(3)+"*+";//公司名称
						_strToFile_ = _strToFile_ + (String)l.get(4)+"*+";//方式
						_strToFile_ = _strToFile_ + (String)l.get(5)+"*+";//申请日
						_strToFile_ = _strToFile_ + (String)l.get(6)+"*+";//完成日
						_strToFile_ = _strToFile_ + (String)l.get(7)+"*+";//退回日
						_strToFile_ = _strToFile_ + (String)l.get(8)+"\n";//状态
						count = count +1;
					}else{
						_strToFile_ = _strToFile_ + "D*+"+ hzbh +"*+";//函证编号
						_strToFile_ = _strToFile_ + "*+";//文件sha256
						_strToFile_ = _strToFile_ + "*+";//文件名
						_strToFile_ = _strToFile_ + (String)l.get(1)+"*+";//分行代码
						_strToFile_ = _strToFile_ + (String)l.get(2)+"*+";//客户号
						_strToFile_ = _strToFile_ + (String)l.get(3)+"*+";//公司名称
						_strToFile_ = _strToFile_ + (String)l.get(4)+"*+";//方式
						_strToFile_ = _strToFile_ + (String)l.get(5)+"*+";//申请日
						_strToFile_ = _strToFile_ + (String)l.get(6)+"*+";//完成日
						_strToFile_ = _strToFile_ + (String)l.get(7)+"*+";//退回日
						_strToFile_ = _strToFile_ + (String)l.get(8)+"\n";//状态
						count = count +1;
					}
	
				}
			}
			
			if((int)json.get("extconfbook_static_num") > 0){
				List extconfbook_list = (List)json.get("extconfbook_static");
				for(int o=0; o<extconfbook_list.size();o++){
					logger.error(extconfbook_list.size());
					List l = (List)extconfbook_list.get(o);
					String hzbh = (String)l.get(0);
					_strToFile_ = _strToFile_ + "D*+"+ hzbh +"*+";//函证编号
					_strToFile_ = _strToFile_ + "*+";//文件sha256
					_strToFile_ = _strToFile_ + "*+";//文件名
					_strToFile_ = _strToFile_ + (String)l.get(1)+"*+";//分行代码
					_strToFile_ = _strToFile_ + (String)l.get(2)+"*+";//客户号
					_strToFile_ = _strToFile_ + (String)l.get(3)+"*+";//公司名称
					_strToFile_ = _strToFile_ + (String)l.get(4)+"*+";//方式
					_strToFile_ = _strToFile_ + (String)l.get(5)+"*+";//申请日
					_strToFile_ = _strToFile_ + (String)l.get(6)+"*+";//完成日
					_strToFile_ = _strToFile_ + (String)l.get(7)+"*+";//退回日
					_strToFile_ = _strToFile_ + (String)l.get(8)+"\n";//状态
					count = count +1;
				}
			}
			
			
			
			
			
			String s = String.format("%09d", count);//左补0
			_strToFile_ = _strToFile_ + "T"+s;
			try {
				
				bufout = new BufferedWriter(new OutputStreamWriter(
						new FileOutputStream(file, true), csvEncode));
	
				bomByte = new byte[]{(byte)0xef,(byte)0xbb,(byte)0xbf};
				bomStr = new String(bomByte,csvEncode);
				bufout.write(bomStr);
//				_strToFile_ = _strToFile_.getBytes("utf-8").toString();
//				ss = _strToFile_.getBytes("GBK");
//				_strToFile_ = new String(ss,"GBK");
				bufout.write(_strToFile_);
				bufout.flush();
				return true;
			} catch (Exception e) {
				return false;
			} finally {
				if (bufout != null) {
					try {
						bufout.close();
					} catch (IOException e) {
					}
					bufout = null;
				}
				//String outputfilePath1 = json.getString("pdffilepath")+"CCCS_"+workdate+".TXT";
				File saveDir_2 = new File(outputfilePath);
				File saveDir_3 = new File(outputPath+"CCCS_"+workdate+".TXT");
				FileUtils.copyFile(saveDir_2, saveDir_3);
				//int a = saveDir_2.getCanonicalPath().compareTo(saveDir_3.getCanonicalPath());
				logger.info("调用结束");
			}
			
		}
		return true;	
				
	}
	
	public static byte[] fileToByte(String path){
			
			BASE64Encoder encoder=new BASE64Encoder();
			FileInputStream fin=null;
			BufferedInputStream bin=null;
			ByteArrayOutputStream baos=null;
			BufferedOutputStream bout=null;
			try {
				fin=new FileInputStream(path);
				bin=new BufferedInputStream(fin);
				baos=new ByteArrayOutputStream();
				bout=new BufferedOutputStream(baos);
				byte[] buffer=new byte[1024];
				int len=bin.read(buffer);
				while(len!=-1){
					bout.write(buffer,0,len);
					len=bin.read(buffer);
				}
				bout.flush();
				byte[] bytes=baos.toByteArray();
				return baos.toByteArray();
			} catch (FileNotFoundException e) {
				
			} catch (IOException e) {
				
			}finally{
				try {
					if(fin ==null && bin == null && bout == null){
						return null;
					}
					fin.close();
					bin.close();
					bout.close();
				} catch (IOException e) {
					//logger1.info("文件转换Base64异常："+e);
				}
			}
			return null;
	}
	public static String sha256(String filename){
		try {
			byte[] bytes = fileToByte(filename);
			MessageDigest digest;
			digest = MessageDigest.getInstance("SHA-256");
			if(bytes == null){
				return "";
			}
			byte[] hash = digest.digest(bytes);
			StringBuilder hexString = new StringBuilder();
			for(byte b:hash){
				String hex = Integer.toHexString(0xff & b);
				if(hex.length() == 1){
					hexString.append('0');
				}
				hexString.append(hex);
			}
		
			return hexString.toString();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public static String toAfe(String filename){
		
		PropertiesUtils utils=new PropertiesUtils();
		utils.getFile("/confes.properties");
		int soTimeout = Integer.parseInt(utils.read("soTimeout"));
		String host3 = utils.read("host3");
		int port4 = Integer.parseInt(utils.read("port4"));
		String host2 = utils.read("host2");
		int port2 = Integer.parseInt(utils.read("port2"));
		CommunicationNatp natp = new CommunicationNatp(host3,port4,host2,port2,soTimeout);
		
		utils.getFile("/bgf.properties");
		String pdffilepath = utils.read("pdffilepath");
		String wfifilepath = utils.read("wfifilepath");
//		System.out.print(pdffilepath);
		
		
		list.clear();
//		s = super.getLogonUser(true);
//		brno = s.getUnit().getBrno();
		String brno = "0000";
		String connect = "smp";
		int natpVersion = 0x30;
		String transCode = "BPBC024";
		String templateCode = "BPBC";
		String reservedCode = "";
		
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		String time=format.format(date);
		SimpleDateFormat formats = new SimpleDateFormat("HHmmss");
		String times=formats.format(date);
		natp.init(natpVersion, transCode, templateCode, reservedCode);
        try {
			natp.pack("respdate",time);
			natp.pack("resptime",times);
	        natp.pack("Brno", brno);
	        natp.pack("basefile", filename);//wfifilepath
	        natp.pack("wfifile", wfifilepath+time);//wfifilepath
	        natp.exchange(connect);
	        String operType="1";
	        String dealStatus = natp.unpack("dealcode",1);
	        System.out.println(dealStatus);
	        if (dealStatus.equals("000000")) {
	        	logger.debug("调用afe返回");
	        }
	        logger.debug("调用afe返回失败："+dealStatus);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        //natp.pack("tellerno", s.getTellerno());
        
        
       
        
       
        
		return null;
	}
	public static void main(String[] args) throws Exception {
		BpbcTxtSerevice ca = new BpbcTxtSerevice();
		List<Integer> colName = new ArrayList();
		colName.add(480);
		colName.add(699);
//		boolean ss = ca.createQRCodeImage("http://www.baidu.com","C:\\Users\\A9010011\\Desktop\\需求\\c.jpg");
//		ca.compositeImageToPDF("C:\\Users\\A9010011\\Desktop\\需求\\c.pdf", "C:\\Users\\A9010011\\Desktop\\需求\\c.jpg", 1, colName);
//		System.out.println(ss);
	}
	

}
